<script setup>
import util from '@/utils/util'
import {Permission, User} from '@/utils/resource'
import {showSaveResponse, validFieldExists, validateForm} from '@/utils/element-helper'
import {nextTick, reactive, ref} from "vue";
import {permissionStore} from "@/store/perminnion";
import {useRouter} from "vue-router";
import Icon from "@components/Icon";

const permissionStoreS = permissionStore()
const router = useRouter()
const props = defineProps({
  id: {
    type: String,
    default: "new"
  },
  parent: {
    type: String,
    default: "0"
  }
})
const isNew = props.id === 'new'
const loading = ref(false)
const form = ref(null)
const permissionsCascader = ref(null)
const id = props.id
const parent = props.parent
const state = reactive({
  addPermissionGroup: false,
  type: 0,
  defaultPermissionGroup: [],
  form: {
    parent: 0,
    parens: 0,
    type: 0,
    checkedPermissionGroup: [],
    priority: 0,
  },
  initForm: {},
  rules: {
    name: [
      {required: true, message: '名称不能为空', trigger: 'blur'},
    ],
    code: [
      {required: true, message: '编码不能为空', trigger: 'blur'},
      {
        validator, trigger: 'blur'
      }
    ],
    type: [
      {required: true, message: '权限类型不能为空', trigger: 'change'},
    ],
  },
})

loading.value = true
setParent()
if (!isNew) {
  loadPermission()
} else {
  //新建
  loadDefaultPermissionGroup()
}
loading.value = false


async function loadPermission() {
  loading.value = true
  let res = await Permission.get(id)
  state.form = util.copy(res.data)
  state.form.parents = state.form.parent
  state.initForm = res.data
  util.disableTreeNode(permissionStoreS.permissionsTree, id)
  await nextTick()
  loading.value = false
}

function setParent() {
  if (!util.isNull(parent)) {
    state.form.parent = Number(parent)
    state.form.parents = state.form.parent
  }
}

function validator(rule, value, callback) {
  validFieldExists(rule, value, callback, state.initForm[rule.field] !== value || isNew, (rule, value) => Permission.exists(rule, value))
}

async function loadDefaultPermissionGroup() {
  loading.value = true
  let res = await Permission.getDefaultPermissionGroup()
  state.defaultPermissionGroup = res.data
  state.form.checkedPermissionGroup = state.defaultPermissionGroup.map(s => s.key)
  await nextTick()
  loading.value = false
}

function submitForm(formName) {
  state.form.ancestors = util.getAncestors(permissionsCascader.value, id)
  let concat = [].concat(state.form.parents);
  state.form.parent = concat[concat.length - 1];
  return validateForm(form.value, formName, () => {
    showSaveResponse(loading.value, () => {
      if (state.addPermissionGroup) {
        state.form.addedGroup = state.form.checkedPermissionGroup.map(key => {
          return {
            code: state.form.code + "." + key,
            name: util.getText(state.defaultPermissionGroup, "key", "value", key),
            icon: util.getText(state.defaultPermissionGroup, "key", "comment", key),
            type: 1,
          }
        })
      }
      return Permission.save(state.form, isNew ? 'post' : 'put')
    }, (res) => router.back())
  })
}

</script>

<template>
  <div>
    <div style="padding-left: 20px">
      <p style="font-size: 20px">权限</p>
      <el-form :model="state.form" label-position="left" :rules="state.rules" ref="form" label-width="140px"
               class="permission-form">
        <el-form-item label="名称" prop="name" class="my-form-item">
          <el-input v-model="state.form.name"></el-input>
        </el-form-item>
        <el-form-item label="编码" prop="code" class="my-form-item">
          <el-input v-model="state.form.code"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon" class="my-form-item">
          <Icon v-model="state.form.icon"></Icon>
        </el-form-item>
        <el-form-item label="父权限" prop="parent" class="my-form-item">
          <el-cascader :options="permissionStoreS.permissionsTree" ref="permissionsCascader"
                       change-on-select clearable class="width100"
                       :props="{
                             value: 'id',
                             label: 'name',
                             children: 'children',
                             checkStrictly: true,
                           }" v-model="state.form.parents"></el-cascader>
        </el-form-item>
        <el-form-item label=" 添加为权限组
              " class="my-form-item" v-show="isNew">
          <el-switch
              v-model="state.addPermissionGroup"
              active-text="已开启"
              inactive-text="已关闭">
          </el-switch>
          <div style="color: #6c757d;">(可快速添加一组默认的子权限,可在数据字典<span
              class="red-span"> default_permission_group </span>中配置)
          </div>
        </el-form-item>
        <el-form-item label="权限类型" prop="type" class="my-form-item">
          <el-select v-model="state.form.type" placeholder="请选择" class="width100">
            <el-option label="页面权限" :value="0"></el-option>
            <el-option label="接口权限" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="默认子权限" prop="parent" class="my-form-item" v-show="state.addPermissionGroup">
          <el-checkbox-group v-model="state.form.checkedPermissionGroup">
            <template v-for="group in state.defaultPermissionGroup" :key="group.key">
              <div>
                <el-checkbox :label="group.key" :key="group.key">
                  <el-icon>
                    <component :is="group.comment"></component>
                  </el-icon>
                  <span
                    class="permission-code-span">&nbsp;{{ group.value }}&nbsp;{{ form.code }}.{{ group.key }}</span>
                </el-checkbox>
              </div>
            </template>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="排序" prop="priority" class="my-form-item">
          <el-input-number v-model="state.form.priority" :min="0" class="width100"></el-input-number>
        </el-form-item>
        <el-form-item label="描述" prop="description" class="my-form-item">
          <el-input type="textarea" :rows="3  " v-model="state.form.description"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div style="padding: 15px">
      <router-link to="/permission">
        <el-button plain round type="info" icon="Back" style="margin-right: 10px">返回</el-button>
      </router-link>
      <el-button plain type="primary" icon="CircleCheck"  @click="submitForm('form')">保存</el-button>
    </div>
  </div>
</template>

<style scoped>
.permission-form {
  width: 90%;
}

.my-form-item {
  max-width: 700px;
}

.red-span {
  color: crimson;
}

.permission-code-span {
  color: #e83e8c;
}

</style>
